import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Popconfirm, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import FormItem from 'antd/lib/form/FormItem';
import CreateForm from './components/CreateForm';
import { transTitle } from '@/utils/utils';
import styles from './index.less';
import Access from '@/components/Access/Access';
import { queryRule, updateRule, addRule, removeRule, queryTree, queryResource } from './service';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (fields, actionRef) => {
  const hide = message.loading('正在删除');
  try {
    await removeRule(fields.id);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [permissionModalVisible, handlePermissionModalVisible] = useState(false);
  const [permissionFormValues, setPermissionFormValues] = useState();
  const [treeData, handleTreeData] = useState(false);
  const [treeValue, handleTreeValue] = useState();
  const [menuValues, setMenuValues] = useState([]);
  const [FormValues, setFormValues] = useState({});
  const [defaultTreeValue, setDefaultTreeValue] = useState([]);
  const [count, setCount] = useState({});

  const actionRef = useRef();


  const TreeOnChange = (value) => {
    if (value &&value.length>0){
      handleTreeValue(value.map(data=>data.value));
    }else{
      handleTreeValue([]);
    }

  };

  const handleSavaContent = async () => {
    try {
      let payload = permissionFormValues;
      let resourceList = [];
      treeValue.map((item) => {
        resourceList.push({ id: item });
      });
      payload.resourceList = resourceList;

      const response = await updateRule(payload);
      handleTreeValue([]);
      handlePermissionModalVisible(false);
      return true;
    } catch (error) {
      return false;
    }
  };
  const handleGetTreeData = async () => {
    try {
      const response = await queryTree({});
      const { data } = response;
      transTitle(data);
      handleTreeData(data);
      return true;
    } catch (error) {
      return false;
    }
  };
  const handleGetResource = async (payload) => {
    try {
      const response = await queryResource(payload);
      const {
        data: { resourceList },
      } = response;
      const reArray = [];
      resourceList.map((item) => {
        reArray.push(item.id);
      });
      return reArray;
    } catch (error) {
      return false;
    }
  };
  useEffect(() => {
    handleGetTreeData();
  }, []);

  /**
   * 更新节点
   * @param fields
   */

  const handleUpdate = async (fields) => {
    const hide = message.loading('正在配置');
    try {
      await updateRule({
        name: fields.name,
        remark: fields.remark,
        id: FormValues.id,
        resourceList: fields.resourceList,
      });
      hide();
      message.success('配置成功');
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      valueType: ' text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '角色名称为必填项',
          },
        ],
      },
    },
    {
      title: '角色权限',
      dataIndex: 'remark',
      valueType: ' text',
      hideInSearch: true,
    },
    {
      title: '资源列表',
      dataIndex: 'resourceList',
      valueType: ' text',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <TreeSelect
              showSearch
              // style={{ width: '300px' }}
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择权限模块"
              allowClear
              treeDataSimpleMode
              treeCheckStrictly={true}
              showCheckedStrategy
              treeCheckable
              treeData={treeData}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={TreeOnChange}

            />
          </FormItem>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Access accessKey={"@updateRole"}>
            <a
              onClick={async () => {
                record.resourceList = await handleGetResource(record.id);
                setFormValues(record);
                handleEditModalVisible(true);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
          </Access>
          <Access accessKey={"@deleteRole"}>
            <Popconfirm
              placement="top"
              title="确定要删除吗?"
              onConfirm={() => {
                handleRemove(record, actionRef);
              }}
              okText="是"
              cancelText="否"
            >
              <a onClick={() => {}}>删除</a>
            </Popconfirm>
          </Access>

        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        bordered
        toolBarRender={() => {
          return (
            <Access accessKey={"@newRole"}>
              <Button
                type="primary"
                onClick={() => {
                  return handleModalVisible(true);
                }}
              >
                <PlusOutlined /> 新增
              </Button>
            </Access>

          );
        }}
        request={(params, sorter, filter) => {
          return queryRule({ ...params, sorter, filter });
        }}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          return list;
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        options={false}
        columns={columns}
        rowSelection={false}
      />
      <CreateForm
        title="新增角色"
        width={800}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            let resourceList = [];

            if (value.resourceList) {
              value.resourceList.map((item) => {
                return resourceList.push({ id: item.value });
              });
              value.resourceList = resourceList;
            }
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          type="form"
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        width={800}
        title="修改角色"
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={createEditModalVisible}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            let resourceList = [];
            value.resourceList.map((item) => {
              return resourceList.push({ id: item.value });
            });
            value.resourceList = resourceList;
            const success = await handleUpdate(value);
            if (success) {
              handleEditModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            initialValues: FormValues,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
